package _2022.hot100._105_从前序与中序遍历序列构造二叉树;

import java.util.HashMap;
import java.util.Map;

/**
 * @author： YHSimon
 * @date： 2022-04-26 14:44
 */


class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;

    TreeNode() {
    }

    TreeNode(int val) {
        this.val = val;
    }

    TreeNode(int val, TreeNode left, TreeNode right) {
        this.val = val;
        this.left = left;
        this.right = right;
    }
}

public class Solution {
    private Map<Integer,Integer> indexMap;
    public TreeNode buildTree(int[] preorder,int[] inorder){
        int n=preorder.length;
        indexMap=new HashMap<>();
        for(int i=0;i<n;i++){
            indexMap.put(inorder[i],i);
        }
        return myBuildTree(preorder,inorder,0,n-1,0,n-1);
    }

    private TreeNode myBuildTree(int[] preorder, int[] inorder, int preorder_left, int preorder_right, int inorder_left, int inorder_right) {
        if (preorder_left>preorder_right){
            return null;
        }

        //前序遍历的第一个节点就是根节点，即根节点在前序序列的位置为preorder_left;
        // 在中序遍历序列中定位根节点
        int inorder_root=indexMap.get(preorder[preorder_left]);

        //构建根节点
        TreeNode root=new TreeNode(preorder[preorder_left]);
        //得到左子树中的节点数目
        int size_left_subtree=inorder_root-inorder_left;
        //递归构造左子树，并连接到根节点
        root.left=myBuildTree(preorder, inorder, preorder_left+1, preorder_left+size_left_subtree, inorder_left, inorder_root-1);
        //递归构造右子树，并连接到根节点
        root.right=myBuildTree(preorder, inorder, preorder_left+size_left_subtree+1, preorder_right, inorder_root+1, inorder_right);
        return root;
    }

}
